package com.kayb.patterns.creational;

/**
 * 单例模式有一下几种线程安全的实现方法：
 * 1. 枚举类：优先使用
 * 2. 静态内部类：懒汉模式，使用类的加载机制来实例化对象
 * 3. 静态常量：饿汉模式，浪费内存
 * 4. 双重锁判断：懒加载，复杂化
 * @author huangkaibin
 * @date 2018-08-28
 **/
public class Singleton {

    private static Singleton instance = null;
    private Singleton() {}

    // 枚举单例
    enum TrafficLamp {
        RED(30){
            public TrafficLamp nextLamp() {
                return GREEN ;
            }
        },
        GREEN(20){
            public  TrafficLamp nextLamp() {
                return YELLOW ;
            }
        },
        YELLOW(10){
            public  TrafficLamp nextLamp() {
                return RED ;
            }
        } ;
        public abstract TrafficLamp nextLamp() ;
        private int time ;
        private TrafficLamp(int time){
            this.time = time ;
            System.out.println(time);
        }
    }

    // 内部静态类
    static class SingletonHolder {
        private static Singleton instance = new Singleton();
    }
    public static Singleton getInstance() {
        return SingletonHolder.instance;
    }

    // 懒汉模式，每次都锁浪费资源
    public static synchronized Singleton newInstance(){
        if(null == instance){
            instance = new Singleton();
        }
        return instance;
    }

    // 双重校验锁
    public static Singleton getInstance2() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {//2
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }

    public static void main(String[] args) {
        System.out.println(TrafficLamp.GREEN);
    }

}
